import React, { useEffect, useState, useRef } from 'react';
import {
  View,
  Image,
  Text
} from '@tarojs/components';
import Taro, { useReachBottom, useDidShow, useRouter } from '@tarojs/taro';
import {
  queryUserImgList,
  queryTaskById
} from '@/api';
import LoadingCss from '@/components/LoadingCss';
import NavBar from '@/components/NavBar';
import './index.scss';

const Myportray = () => {
  const router = useRouter();
  const [titleBarHeight, setTitleBarHeight] = useState(0);
  const [list, setList] = useState([]);
  const [sceduleImgShow, setSceduleImgShow] = useState(false);
  const pageNo = useRef(1);
  const siv = useRef(null);
  const [hasMore, setHasMore] = useState(true);
  const [info, setInfo] = useState({});

  useDidShow(() => {
    Taro.getSystemInfo({
      success: (res) => {
        let height = res.titleBarHeight + res.statusBarHeight
        setTitleBarHeight(height)
      }
    });
    let params = router.params;
    let TaskId = params.TaskId;
    if (TaskId) {
      onLoadTask();
    }
    onLoadData();
  });

  useEffect(()=>{
    return () => {
      clearInterval(siv.current)
    };
  }, []);

  useEffect(()=>{
    if (info.id && list.length > 0) {
      let newArr = [info, ...list];
      setInfo({});
      setList(newArr);
    }
  }, [info, list])

  const onLoadTask = () => {
    let params = router.params;
    let TaskId = params.TaskId;
    siv.current = setInterval(()=>{
      queryTaskById({task_id: TaskId})
        .then(res=>{
          if (res.Status == "Success") {
            clearInterval(siv.current);
            let data = {};
            data = {
              id: res.ImgId,
              img: res.Result.data,
              task_id: TaskId,
              tmpl: res.Tmpl
            }
            setInfo(data);
            setSceduleImgShow(false);
          } else {
            setSceduleImgShow(true);
          }
        });
    }, 2000)
  }
  // useEffect(()=>{
  //   TaskId
  // })

  // const pollingTask = (id) => {
  //   timerId = setInterval(async () => {
  //     if (id === "stop") {
  //       clearInterval(timerId); // Stop the polling if 'id' is 'stop'
  //       return;
  //     }
  //     try {
  //       const res = await queryTaskById(id);
  //       // sceduleImgShow.value = true;
  //       setSceduleImgShow(true);
  //       if (res.Code === "InvalidParams") {
  //         clearInterval(timerId);
  //       }
  //       if (res.Code) {
  //         if (res.Code !== 200) {
  //           uni.showToast({
  //             title: "生成失败",
  //             icon: "error"
  //           });
  //           clearInterval(timerId);
  //           return;
  //         }
  //       }
  //       if (res.Status === "Pending") {
  //         if (res.RemainSeconds > 3600) {
  //           pollingInterval.value = 300000;
  //         } else if (res.RemainSeconds > 1800 && res.RemainSeconds < 3600) {
  //           pollingInterval.value = 180000;
  //         } else if (res.RemainSeconds < 1800 && res.RemainSeconds > 600) {
  //           pollingInterval.value = 60000;
  //         } else {
  //           pollingInterval.value = 2000;
  //         }
  //       }
  //       // 成功..
  //       if (res.Status === "Success") {
  //         clearList();
  //         sceduleImgShow.value = false;
  //         if (Environment === "develop" || Environment === "trial") {
  //           test_userstore.closePolling();
  //           clearInterval(timerId);
  //           return;
  //         } else {
  //           userstore.closePolling();
  //           clearInterval(timerId);
  //           return;
  //         }
  //         clearInterval(timerId); // Stop the polling if 'id' is 'stop'
  //         return;
  //       }
  //     } catch (error) {
  //       // 处理请求失败的情况
  //       console.error("Error in pollingTask:", error);
  //       clearInterval(timerId);
  //       return;
  //     }
  //   }, pollingInterval.value);
  // };

  useReachBottom(()=>{
    if (hasMore) {
      pageNo.current = pageNo.current + 1;
      onLoadData();
    }
  });

  const onLoadData = () => {
    let params = {
      page: pageNo.current,
      page_size: 20,
    }
    queryUserImgList(params)
      .then(res=>{
        let data = res.list || [];
        let arr = [];
        if (pageNo.current === 1) {
          arr = data;
        } else {
          arr = [...list, ...data];
        }
        if (res.list.length < 20) {
          setHasMore(false)
        }
        setList(arr);
      })
  }

  const doBack = () => {

  }

  const onShowDetail = (obj) => {
    Taro.navigateTo({
      url: `/pages/subpages/myportray/detail?id=${obj.id}&img=${obj.img}&tmpl_id=${obj.tmpl.id}&tmpl_img=${obj.tmpl.img}&tmpl_tmb_img=${obj.tmpl.tmb_img}&tmpl_name=${obj.tmpl.tmpl_name}&use_num=${obj.tmpl.use_num}&number=${obj.tmpl.number}&backdrop_img=${obj.tmpl.backdrop_img}`
    });
  }

  return (
    <View className='myportray_container'>
      {/* <NavBar
        title="我的写真"
        onClick={()=>{doBack()}}
      /> */}
      <View
        className='myportray_section'
        style={{
          paddingTop: `${titleBarHeight}px`
        }}
      >
        <View
          style={{
            height: `calc(100vh - ${titleBarHeight}px)`
          }}
          className='myportray_view'
        >
          {
            sceduleImgShow ? (
              <View
                className='myportray_view_section'
              >
                <LoadingCss />
              </View>
            ) : null
          }
          {
            list.map(item=>
              <View
                className='myportray_view_section'
                key={item.id}
                onClick={()=>{onShowDetail(item)}}
              >
                <Image
                  src={item.img}
                  className='myportray_view_section_img'
                  mode='aspectFill'
                />
              </View>
            )
          }
        </View>
      </View>
    </View>
  )
}
export default Myportray;
